package user

import (
	"context"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateUserLogic) CreateUser(req *types.CreateSystemUserReq) (resp *types.BaseMsgResp, err error) {
	if req.Username == nil || len(strings.TrimSpace(*req.Username)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "user.usernameRequired"))
	}

	if req.Password == nil || len(strings.TrimSpace(*req.Password)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "user.passwordRequired"))
	}

	res, err := l.svcCtx.BackendRpc.CreateUser(l.ctx, &backendclient.UserInfo{
		Username:   req.Username,
		Nickname:   req.Nickname,
		Password:   req.Password,
		RoleIds:    req.RoleIds,
		Status:     req.Status,
		Email:      req.Email,
		Mobile:     req.Mobile,
		Department: req.Department,
		// Avatar:      req.Avatar,
		Description: req.Description,
		HomePath:    req.HomePath,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
